package com.lab.idea.bl.listen;

import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.googlecode.aviator.AviatorEvaluator;
import com.lab.idea.bl.util.LabUtil;
import com.lab.idea.bl.util.TipWindow;
import com.lab.idea.module.method.ScriptUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;

import javax.annotation.Resource;
import java.net.InetAddress;

/**
 * 系统启动完成后执行
 * @author mao
 */
@Slf4j
@Component
public class StartReadyEventListener implements ApplicationListener<ApplicationStartedEvent> {

    @Value("${conf}")
    private String conf;

    @Value("${server.port}")
    private int port;

    @Resource
    private WebApplicationContext applicationContext;



    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        checkLicense();
        try {
            AviatorEvaluator.addStaticFunctions("LabUtil", LabUtil.class);
            String openUrl = String.format("http://127.0.0.1:%s",port);
            InetAddress localhost = NetUtil.getLocalhost();
            if (localhost != null) {
                openUrl = String.format("http://%s:%s",localhost.getHostAddress(),port);
            }
            LabUtil.openBrowse(openUrl);
            TipWindow.show("启动成功!", 2000);
        }catch (Exception e) {
            TipWindow.error(e.getMessage(),5000);
            log.error("----------窗口启动失败----------",e);
        }
    }

    /**
     * 授权信息验证
     */
    private void checkLicense() {
        try {
            log.info("验证....");
        }catch (Exception e){
            log.error("授权验证失败:{}",e.getMessage());
            TipWindow.show(e.getMessage(),5000);
            System.exit(SpringApplication.exit(applicationContext));
        }
    }
}
